<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="item-form"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number 
          v-model="form.price" 
          :min="0" 
          :precision="2"
          :step="0.01"
          placeholder="请输入价格"
        />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number 
          v-model="form.stock" 
          :min="0" 
          :precision="0"
          placeholder="请输入库存"
        />
      </el-form-item>
      <el-form-item label="商品图片" prop="image">
        <el-upload
          class="avatar-uploader"
          action="/api/upload"
          :show-file-list="false"
          :on-success="handleImageSuccess"
          :before-upload="beforeImageUpload"
        >
          <img v-if="form.image" :src="form.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="类目" prop="category">
        <el-input v-model="form.category" placeholder="请输入类目" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="form.brand" placeholder="请输入品牌" />
      </el-form-item>
      <el-form-item label="规格" prop="spec">
        <el-input v-model="form.spec" placeholder="请输入规格" />
      </el-form-item>
      <el-form-item label="是否广告" prop="isAD">
        <el-switch v-model="form.isAD" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import type { ItemDTO } from '@/api/item'

const props = defineProps<{
  visible: boolean
  title: string
  itemData?: ItemDTO
}>()

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(props.visible)
const formRef = ref<FormInstance>()

const form = reactive<ItemDTO>({
  name: '',
  price: 0,
  stock: 0,
  image: '',
  category: '',
  brand: '',
  spec: '',
  sold: 0,
  commentCount: 0,
  isAD: false,
  status: 1
})

const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请输入类目', trigger: 'blur' }
  ],
  brand: [
    { required: true, message: '请输入品牌', trigger: 'blur' }
  ],
  spec: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ]
}

watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
})

watch(() => props.itemData, (val) => {
  if (val) {
    Object.assign(form, val)
  } else {
    Object.assign(form, {
      name: '',
      price: 0,
      stock: 0,
      image: '',
      category: '',
      brand: '',
      spec: '',
      sold: 0,
      commentCount: 0,
      isAD: false,
      status: 1
    })
  }
}, { immediate: true })

const handleClose = () => {
  formRef.value?.resetFields()
}

const handleImageSuccess = (response: any) => {
  form.image = response.data
}

const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      emit('success', { ...form })
    }
  })
}
</script>

<style scoped>
.item-form {
  padding: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 